<?php

namespace app\models\cash;

use app\models\user\User;
use app\models\user\UserAccount;
use wanyue\basic\BaseModel;
use wanyue\traits\ModelTrait;

/**
 * TODO 映票提现Model
 */
class Giftvotes extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'cash_giftvote';

    use  ModelTrait;
    public static $status = [-1=>'拒绝',0=>'申请中',1=>'已到账'];

    //提现列表
    public static function getList($uid,$page = 0, $limit = 0 )
    {
        if ($uid<1 || $page<1 || $limit<1) return [];


        $model = self::where('uid',$uid)->field('id,money,orderno,status,addtime')->order('id desc');
        if ($page) $model->page($page, $limit);
        $list = $model->select()->toArray();

        foreach ($list as &$item){
            $item['addtime']=date('Y-m-d H:i',$item['addtime']);
            $item['title']='订单'.$item['orderno'];
            $item['status_txt']=self::$status[$item['status']];
        }

        return $list;
    }

    //提现中金额
    public static function cashmoney($uid )
    {
        $money= self::where(['uid'=>$uid,'status'=>0])->sum('money');
        if(!$money){
            $money='0.00';
        }
        return $money;
    }

    //提现
    public static function cash($uid,$money,$accountid)
    {

        if($uid<1 || $money<=0 || $accountid<1) return self::setErrorInfo('信息错误');



        $userinfo=User::getUserInfo($uid,'votes');

        if($userinfo['votes']<$money) return self::setErrorInfo('余额不足');

        //if($money<100) return self::setErrorInfo('最低提现金额为100元');

        $info=UserAccount::getInfo($accountid);
        if(!$info || $info['uid']!=$uid) return self::setErrorInfo('提现账号信息错误');


        $orderno=$uid.'_'.time();
        $addtime=time();
        $type=$info['type'];
        $bank=$info['bank'];
        $account=$info['account'];
        $name=$info['name'];

        self::beginTrans();
        $res=self::create(compact('uid','money','orderno','addtime','type','bank','account','name'));

        $res2=User::decField($uid,'votes',$money);

        if($res && $res2){
            self::commitTrans();
            return true;
        }else{
            self::rollbackTrans();
            return self::setErrorInfo('操作失败');
        }
    }

}